import logging
from spyne import Application, rpc, ServiceBase, Unicode
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from wsgiref.simple_server import make_server
from xml.etree import ElementTree as ET

#从配置文件读取配置，并根据指定节点数据返回
def get_config_value(node_id):
    # Parse the XML file
    tree = ET.parse('config.xml')
    root = tree.getroot()

    # Find the specified node
    xpath = f"./entry[@id='{node_id}']"
    entry_node = root.find(xpath)

    if entry_node is not None:
        if entry_node.get('id') == node_id:
            # Extract all data under the found node
            node_data = ET.tostring(entry_node, encoding='utf-8').decode('utf-8')
            return node_data
    else:
        return None

# 定义服务
class DemoService(ServiceBase):

    @rpc(Unicode, _returns=Unicode)
    def sayHello(self, msg):
        print("sayHello msg: ", msg)
        return 'Hello, ' + msg

    @rpc(Unicode, _returns=Unicode)
    def excuteXml(ctx, request_xml):
        try:
            print("excuteXml request_xml : ", request_xml)
            root = ET.fromstring(request_xml)
            node_id = root.find('.//busiCode').text
            print("excuteXml node_id: ", node_id)
            response_xml = get_config_value(node_id)
            return response_xml

        except Exception as e:
            # Log the exception
            logging.error(f"Exception occurred: {e}")
            # You can also raise the exception if you want it to propagate further
            raise

# 启动Soap服务
def create_soap_server():
    host = "127.0.0.1"
    port = 8000
    service = "soap_point"
    tns = 'http://www.example.com/'
    soap_app = Application([DemoService], tns,
                           in_protocol=Soap11(validator='lxml'),
                           out_protocol=Soap11())
    wsgi_app = WsgiApplication(soap_app)

    server = make_server(host, port, wsgi_app)
    print('WebService Started： http://' + host + ':' + str(port) + '/' + service + '/?wsdl')
    server.serve_forever()

if __name__ == '__main__':
    create_soap_server()
